package cn.xuguowen.user.designPatten.factory.config_factory;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * ClassName: ConfigFactory
 * Package: cn.xuguowen.user.designPatten.factory.config_factory
 * Description:
 * 配置文件+简单工厂实现解耦
 * Spring下的bean实例对象的创建就是这样的
 *
 * @Author 徐国文
 * @Create 2023/4/27 15:28
 * @Version 1.0
 */
public class ConfigFactory {

    private static Map<String, Coffee> coffeeMap = new HashMap<>();

    static {
        try {
            // 1.加载配置文件
            Properties prop = new Properties();
            prop.load(ConfigFactory.class.getClassLoader().getResourceAsStream("factory/bean.properties"));

            // 2.遍历配置文件中的所有key
            Set<Object> keys = prop.keySet();
            if (keys != null && keys.size() > 0) {
                for (Object key : keys) {
                    // 3.根据key获取value值
                    String className = prop.getProperty((String) key);
                    // 4.利用反射创建对象
                    Class<?> clazz = Class.forName(className);
                    Coffee coffee = (Coffee) clazz.newInstance();
                    // Class<?> clazz = ConfigFactory.class.getClassLoader().loadClass(className);

                    // 5.将创建好的对象存储到map集合中
                    coffeeMap.put((String) key, coffee);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Coffee getCoffee(String coffeeType) {
        return coffeeMap.get(coffeeType);
    }
}
